<template>
  <h2>组合式api</h2>
  <div>总数量：{{ goodsNum }}</div>
  <div>总价格：{{ goodsTotal }}</div>
  <div>详细地址：{{ detailAddress }}</div>
  <button @click="changeValue">修改计算属性的值</button>
</template>

<script setup>
import { ref, computed } from "vue"


const arr = ref([
  { id: 1001, name: 'ipad', price: 200, num: 2 },
  { id: 1002, name: 'ipad2', price: 200, num: 3 },
  { id: 1003, name: 'ipad3', price: 20, num: 5 },
  { id: 1004, name: 'ipad4', price: 200, num: 4 },
])

//商品数量
const goodsNum = computed(() => {
  const num = arr.value.reduce((acc, cur) => acc + cur.num, 0)
  return num
})

const address = ref('北京市')
const detailAddress = computed({
  //获取
  get() {
    return address.value + '海淀区'
  },
  //修改
  set(v) {
    console.log('v:', v)
    address.value = v
  }
})


//商品总价
const goodsTotal = computed(() => {
  const total = arr.value.reduce((acc, cur) => acc + (cur.price * cur.num), 0)

  return total
})


const changeValue = () => {
  // console.log(arr)
  // console.log(goodsNum)
  //goodsNum.value = 90
  detailAddress.value = '河南省'
}


</script>

<style scoped lang="scss"></style>
